package com.bayihouse.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MyDateUtils {


    private static SimpleDateFormat simpleDateFormat = null;

    public static Date getBirthday(String identity) throws ParseException {
        String year = identity.substring(6, 10);
        String month = identity.substring(10, 12);
        String day = identity.substring(12, 14);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(year + "-" + month + "-" + day);
    }


    public static Integer getAge(Date birthday) throws ParseException {
        if (birthday == null) {
            return null;
        }
        Calendar birthdayCalendar = Calendar.getInstance();
        birthdayCalendar.setTime(birthday);
        Calendar nowCalendar = Calendar.getInstance();
        nowCalendar.setTime(new Date());
        Integer age = nowCalendar.get(Calendar.YEAR) - birthdayCalendar.get(Calendar.YEAR);
        age += (nowCalendar.get(Calendar.MONTH) - birthdayCalendar.get(Calendar.MONTH)) >= 0 ? 0 : -1;
        return age;
    }


    public static String dateToString(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = getInstance();
        return simpleDateFormat.format(date);
    }


    public static String dateToString(Date date, String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = getInstance(format);
        return simpleDateFormat.format(date);
    }


    private static SimpleDateFormat getInstance() {
        if (simpleDateFormat == null) {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
        return simpleDateFormat;
    }


    private static SimpleDateFormat getInstance(String format) {
        if (simpleDateFormat == null) {
            return new SimpleDateFormat(format);
        }
        simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat;
    }
}
